using System;
using System.Collections.Generic;
using UnityEngine;
using WorldMapBase.Tile.Pool;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Gameplay.RTS
{
    public class BattleEffectPool
    {
        private Dictionary<string,RtsEffectPool> effectPools = new Dictionary<string, RtsEffectPool>();
        private GameObject effectRoot;
        private ResLoader _resLoader;

        public void Init()
        {
            effectPools.Clear();
            effectRoot = new GameObject("BattleEffectPool");
            effectRoot.transform.parent = PoolCollectionManager.GetInstance("PoolCollectionManager").transform;
            _resLoader = ResLoader.Alloc();
        }

        public void GetEffect(string path,Action<GameObject> onOver)
        {
            RtsEffectPool effectPool;
            if (!effectPools.TryGetValue(path, out effectPool))
            {
                _resLoader.Add2Load(path + ".prefab", (success,name,asset) =>
                {
                    if (success)
                    {
                        RtsEffectPool newPool;
                        if (!effectPools.TryGetValue(path, out newPool))
                        {
                            newPool = new RtsEffectPool(10,1,asset as GameObject,effectRoot.transform);
                            effectPools.Add(path,newPool);
                        }
                        onOver(newPool.GetItem());
                    }
                }).Load();
            }
            else
            {
                onOver(effectPool.GetItem());
            }
        }

        public void RecoverEffect(string path,GameObject effect)
        {
            if (effectPools.TryGetValue(path, out var pool))
            {
                pool.RecoverItem(effect);
            }
        }

        public void Update()
        {
            int total = 0;
            foreach (var pair in effectPools)
            {
                var pool = pair.Value;
#if UWA
                UWAEngine.LogValue(pool.Name, pool.AliveCount);
#endif
                total += pool.AliveCount;
            }
#if UWA
            UWAEngine.LogValue("Effect", total);
#endif
            
        }

        public void Dispose()
        {
            _resLoader.Recycle2Cache();
        }
    }
}
